﻿<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>列表列表</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600" rel="stylesheet">
    <link rel="stylesheet" href="/css/reset.min.css">
    <link rel="stylesheet" href="/css/style.css">

</head>
<body>


<div class="wrapper">

    <div class="container">
        <div class="left">
            <div class="top">
                <div >
                    <button type="button" onclick="window.location.href='/msg/friends'" class="search">好友列表</button>
                    <button type="button" onclick="window.location.href='/msg/chatting'" class="search">聊天列表</button>
                </div>
            </div>
            <ul  class="people">
                <li  th:each="user : ${users}" class="person" th:attr="data-chat='person'+${user.id}">
                    <img th:src="${user.avatar}" alt="" />
                    <span class="name" th:text="${user.nickname}">...</span>
                    <span class="time" th:text="${#dates.format(user.lastChatTime,'hh:mm')}">..</span>
                    <span class="preview" th:text="${user.mobile}"></span>
                </li>

            </ul>
        </div>
        <div class="right">
            <div class="top">
                <span>To: <span class="name" th:text="${fNickName}" ></span></span></div>
            <div th:each="user : ${users}" class="chat" th:id="${user.id}" th:attr="data-chat='person'+${user.id}">
                <div th:attr="id='id:'+${user.id}" class="conversation-start">
                    <span th:text="${#dates.format(user.lastChatTime,'yyyy-MM-dd HH:mm:ss')}"></span>
                </div>
                <div th:each="usermsg:${user.userMsgs}" class="bubble you" th:attr="class='bubble '+${usermsg.sendId!=session.currentId?'you':'me'}">
                    [[${usermsg.msg}]]
                </div>
            </div>
            <div class="write">
                <a  class="write-link attach"></a>
                <input id="msg" type="text" />
                <a  class="write-link smiley"></a>
                <a  id="send" href="javascript:void(0);" onclick="sendMsg()" class="write-link send"></a>
            </div>
        </div>
    </div>
</div>

<script  th:inline="javascript">

    document.querySelector('.chat[data-chat=person'+[[${fId}]]+']').classList.add('active-chat');
    document.querySelector('.person[data-chat=person'+[[${fId}]]+']').classList.add('active');

    var friends = {
            list: document.querySelector('ul.people'),
            all: document.querySelectorAll('.left .person'),
            name: '' },

        chat = {
            container: document.querySelector('.container .right'),
            current: null,
            person: null,
            name: document.querySelector('.container .right .top .name') };


    friends.all.forEach(function (f) {
        f.addEventListener('mousedown', function () {
            f.classList.contains('active') || setAciveChat(f);
        });
    });

    function setAciveChat(f) {
        // console.log("关闭webSocket");
        // CHAT.wsclose();
        friends.list.querySelector('.active').classList.remove('active');
        f.classList.add('active');
        chat.current = chat.container.querySelector('.active-chat');
        chat.person = f.getAttribute('data-chat');
        chat.current.classList.remove('active-chat');
        chat.container.querySelector('[data-chat="' + chat.person + '"]').classList.add('active-chat');
        friends.name = f.querySelector('.name').innerText;
        chat.name.innerHTML = friends.name;
        CHAT.init();
        console.log("建立websockt");
    }
</script>
<script th:inline="javascript" type="text/javascript">

    function sendMsg(){
        var msg_text_val = document.getElementById("msg").value;
        if (msg_text_val.length === 0) {
            return;
        }

        var personId = document.getElementsByClassName('person active')[0].getAttribute("data-chat");
        //当前输入框id
        var fId =personId.substr(6,personId.length);

        appendMsg(msg_text_val);

        // 情况消息文本框中的内容
        msg_text_val.value = "";
        // 发送消息完毕之后，情况input
        document.getElementById("msg").value="";
        var meId =[[${session.currentId}]];
        // 构建ChatMsg
        var chatMsg = new app.ChatMsg(meId, fId, msg_text_val, null);
        // 构建DataContent
        var dataContent = new app.DataContent(app.CHAT, chatMsg, null);
        CHAT.chat( JSON.stringify(dataContent));

    }

    function receiveMsg(msg,sendId) {

        var msgHtml = '<div class="bubble you">' +
            msg +
            '</div>';
        var personId = document.getElementsByClassName('person active')[0].getAttribute("data-chat");
        //当前输入框id
         var fId =personId.substr(6,personId.length);


        if(sendId==fId){
            var msg_list = document.getElementsByClassName('chat active-chat')[0];
            msg_list.insertAdjacentHTML("beforeend", msgHtml);
        }else {
            var msg_list = document.getElementById(sendId);
            msg_list.insertAdjacentHTML("beforeend", msgHtml);
        }
    }


    function appendMsg(msg) {
        var msgHtml = '<div class="bubble me">' +
            msg +
            '</div>';
        var msg_list = document.getElementsByClassName('chat active-chat')[0];
        msg_list.insertAdjacentHTML("beforeend", msgHtml);

    }


</script>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="application/javascript" src="/js/app.js"></script>
<script th:inline="javascript" type="text/javascript">
    // 构建聊天业务CHAT
    window.CHAT = {
        socket: null,
        init: function() {
            if ("WebSocket" in window) {

                // 如果当前的状态已经连接，那就不需要重复初始化websocket
                if (CHAT.socket != null
                    && CHAT.socket != undefined
                    && CHAT.socket.readyState == WebSocket.OPEN) {
                    return false;
                }

                var url =[[${wxUrl}]];
                CHAT.socket = new WebSocket(url);
                CHAT.socket.onopen = CHAT.wsopen,
                    CHAT.socket.onclose = CHAT.wsclose,
                    CHAT.socket.onerror = CHAT.wserror,
                    CHAT.socket.onmessage = CHAT.wsmessage;

            } else {
                alert("浏览器不支持websocket");
            }
        },
        chat: function(msg) {

            // 如果当前websocket的状态是已打开，则直接发送， 否则重连
            if (CHAT.socket != null
                && CHAT.socket != undefined
                && CHAT.socket.readyState == WebSocket.OPEN) {
                CHAT.socket.send(msg);
            }

            // 渲染快照列表进行展示
            // loadingChatSnapshot();
        },
        reChat: function(msg) {
            console.log("消息重新发送...");
            CHAT.socket.send(msg);
        },
        wsopen: function() {
            console.log("websocket连接已建立...");
            var meId =[[${session.currentId}]];
            // 构建ChatMsg
            var chatMsg = new app.ChatMsg(meId, null, null, null);
            // 构建DataContent
            var dataContent = new app.DataContent(app.CONNECT, chatMsg, null);
            // 发送websocket
            CHAT.chat(JSON.stringify(dataContent));

            // 每次连接之后，获取用户的未读未签收消息列表
            // fetchUnReadMsg();

            // 定时发送心跳
            setInterval("CHAT.keepalive()", 10000);
        },
        wsmessage: function(e) {
            console.log("接受到消息：" + e.data);

            // 转换DataContent为对象
            var dataContent = JSON.parse(e.data);
            var action = dataContent.action;

            var chatMsg = dataContent.chatMsg;
            var msg = chatMsg.msg;
            var friendUserId = chatMsg.senderId;
            var myId = chatMsg.receiverId;
            receiveMsg(msg,friendUserId);

            // 接受到消息之后，对消息记录进行签收 测试页面不需要
            var dataContentSign = new app.DataContent(app.SIGNED, null, chatMsg.msgId);
            CHAT.chat(JSON.stringify(dataContentSign));
        },
        wsclose: function() {
            console.log("连接关闭...");
        },
        wserror: function() {
            console.log("发生错误...");
        },

        keepalive: function() {
            // 构建对象
            var dataContent = new app.DataContent(app.KEEPALIVE, null, null);
            // 发送心跳
            CHAT.chat(JSON.stringify(dataContent));

            // // 定时执行函数
            // fetchUnReadMsg();
            // fetchContactList();
        }
    };
</script>
</body>
</html>